<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="论文标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入论文标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="论文类型" prop="paperType">
        <el-select v-model="queryParams.paperType" placeholder="请选择论文类型" clearable>
          <el-option label="期刊论文" value="期刊论文" />
          <el-option label="会议论文集" value="会议论文集" />
          <el-option label="报纸" value="报纸" />
          <el-option label="学位论文" value="学位论文" />
        </el-select>
      </el-form-item>
      <el-form-item label="本人排名" prop="authorRank">
        <el-input-number
            v-model="queryParams.authorRank"
            placeholder="本人排名"
            :min="1"
            :max="50"
            controls-position="right"
        />
      </el-form-item>

      <el-form-item label="收录检索" prop="indexing">
        <el-select
            v-model="queryParams.indexing"
            placeholder="请选择收录检索"
            clearable
            multiple
            collapse-tags
            style="width: 100%"
        >
          <el-option label="全选" value="all" @click="toggleAllSelection" />
          <el-option label="SCI" value="SCI" />
          <el-option label="SCIE" value="SCIE" />
          <el-option label="SSCI" value="SSCI" />
          <el-option label="ESCI" value="ESCI" />
          <el-option label="自然指数杂志" value="自然指数杂志" />
          <el-option label="CSSCI" value="CSSCI" />
          <el-option label="CSSCI扩展版" value="CSSCI扩展版" />
          <el-option label="CSCD-C" value="CSCD-C" />
          <el-option label="CSCD-E" value="CSCD-E" />
          <el-option label="SCD" value="SCD" />
          <el-option label="AHCI" value="AHCI" />
          <el-option label="EI" value="EI" />
          <el-option label="CPCI-S(ISTP)" value="CPCI-S(ISTP)" />
          <el-option label="CPCI-SSH(ISSHP)" value="CPCI-SSH(ISSHP)" />
          <el-option label="PKU(中文核心)" value="PKU(中文核心)" />
          <el-option label="科技核心" value="科技核心" />
          <el-option label="国家级期刊" value="国家级期刊" />
          <el-option label="省级期刊" value="省级期刊" />
          <el-option label="校内核心" value="校内核心" />
          <el-option label="会议论文" value="会议论文" />
          <el-option label="其它" value="其它" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="papersList" @selection-change="handleSelectionChange" ref="paperTable">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上传者" align="center" prop="nickName" />
      <el-table-column label="论文标题" align="center" prop="title" />
      <el-table-column label="论文类型" align="center" prop="paperType" />
      <el-table-column label="本人排名" align="center" prop="authorRank" />
      <el-table-column label="收录检索" align="center" prop="indexing" />
      <el-table-column label="发表时间" align="center" prop="publishDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Download"
              @click="download(scope.row)"
              :disabled="!scope.row.pdfPath"
          >下载</el-button>
          <el-button
              size="mini"
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['result:papers:edit']"
          >详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <paper-export v-model="showExportDialog" :papers="exportData" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { treeselect } from "@/api/system/dept";
import PaperExport from "@/components/result/ExportDialog/paperExport.vue";
import { listPapers, getPapers, delPapers, addPapers, updatePapers, getPapersByIds } from "@/api/result/papers"
import {useRouter} from "vue-router";
import {findUser} from "@/api/system/user";
const router = useRouter();

const queryForm = ref(null)
const form = ref(null)
const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const open = ref(false)
const papersList = ref([])
const deptName = ref("");
const deptOptions = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
const paperTable = ref(null);
const dateRange = ref(null);
const showExportDialog = ref(false);
const exportData = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nickName: null,
  title: null,
  paperType: null,
  researchField: null,
  authorRank: null,
  correspondingAuthor: null,
  journalName: null,
  indexingList: null,
  publishDate: null,
  // 新增发表时间范围参数
  publishTimeStart: null,
  publishTimeEnd: null,
  doi: null,
  citationCount: null,
  keywords: null,
  pageRange: null,
  projectId: null,
  authorInfo: null,
  impactFactor: null,
  volumeNumber: null,
  issueNumber: null,
  issn: null,
  cnNumber: null,
  abstract: null,
  remarks: null,
  pdfPath: null,
  syncStatus: null,
  createdAt: null,
  updatedAt: null,
  userId: null,
  deptId: null,
  postIds: [],
  roleIds: [],
})

const formData = reactive({
  id: null,
  nickName: null,
  title: null,
  paperType: null,
  researchField: null,
  authorRank: null,
  correspondingAuthor: null,
  journalName: null,
  indexingList: null,
  publishDate: null,
  doi: null,
  citationCount: null,
  keywords: null,
  pageRange: null,
  projectId: null,
  authorInfo: null,
  impactFactor: null,
  volumeNumber: null,
  issueNumber: null,
  issn: null,
  cnNumber: null,
  abstract: null,
  remarks: null,
  pdfPath: null,
  syncStatus: "0",
  createdAt: null,
  updatedAt: null,
  userId: null,
  postIds: [],
  roleIds: [],
})

const download = (row) => {
  if (row.pdfPath) {
    console.log('下载:', row.pdfPath);
    window.open(row.pdfPath, '_blank');
  } else {
    ElMessage.warning('该报告没有可下载的PDF文件');
  }
};
const toggleAllSelection = () => {
  if (queryParams.indexingList?.includes('all')) {
    queryParams.indexingList = []
  } else {
    queryParams.indexingList = [
      'SCI', 'SCIE', 'SSCI', 'ESCI', '自然指数杂志', 'CSSCI', 'CSSCI扩展版',
      'CSCD-C', 'CSCD-E', 'SCD', 'AHCI', 'EI', 'CPCI-S(ISTP)', 'CPCI-SSH(ISSHP)',
      'PKU(中文核心)', '科技核心', '国家级期刊', '省级期刊', '校内核心', '会议论文', '其它'
    ]
  }
}

onMounted(() => {
  getList()
})

/** 查询论文列表 */
function getList() {
  loading.value = true
  listPapers(queryParams).then(response => {
    papersList.value = response.rows
    console.log("papersList.value ", papersList.value)
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = { ...formData }
  form.value.syncStatus = "0"
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  // 打印dateRange原始值
  console.log("选择的日期范围（dateRange）：", dateRange.value);
  // 处理发表时间范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.publishTimeStart = dateRange.value[0];
    queryParams.publishTimeEnd = dateRange.value[1];
    // 打印赋值后的参数
    console.log("赋值后的publishTimeStart：", queryParams.publishTimeStart);
    console.log("赋值后的publishTimeEnd：", queryParams.publishTimeEnd);
  } else {
    queryParams.publishTimeStart = null;
    queryParams.publishTimeEnd = null;
    console.log("未选择日期或格式错误，参数置为null");
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryForm.value.resetFields();
  queryParams.postIds = [];
  queryParams.roleIds = [];
  dateRange.value = []; // 重置日期范围
  queryParams.publishTimeStart = null; // 清空时间参数
  queryParams.publishTimeEnd = null;
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log('编辑:', row.id);
  router.push({ path: '/main/papers/edit', query: { id: row.id } });
}

/** 导出按钮操作 */
async function handleExport() {
  if (!paperTable.value) {
    ElMessage.warning('表格未加载，请稍后再试');
    return;
  }

  const selectedRows = paperTable.value.getSelectionRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要导出的论文');
    return;
  }

  // 提取选中论文的 id
  const selectedIds = selectedRows.map(item => item.id);
  console.log('handleExport', selectedIds)
  try {
    // 获得具体信息并处理indexing字段（字符串兼容处理）
    const res = await getPapersByIds(selectedIds);
    console.log('handleExport', res)
    if (res.code === 200 && res.data) {
      // 处理导出数据中的indexing字段（确保为字符串，避免数组操作报错）
      const processedData = res.data.map(paper => ({
        ...paper,
        // 若indexing是数组则转为字符串，否则保持原样
        indexing: Array.isArray(paper.indexing) ? paper.indexing.join(',') : paper.indexing
      }));
      // 打开导出对话框并传递处理后的数据
      showExportDialog.value = true;
      exportData.value = processedData;
    } else {
      ElMessage.error('获取论文数据失败');
    }
  } catch (error) {
    ElMessage.error('获取论文数据时发生错误');
  }
}
</script>
